package cz.proks.schoolpupilbook.gae.converter;

import com.google.appengine.api.datastore.KeyFactory;

import cz.proks.schoolpupilbook.gae.dao.CourseDAO;
import cz.proks.schoolpupilbook.gae.dao.UserDAO;
import cz.proks.schoolpupilbook.gae.dbo.UserCourseRelationDBO;
import cz.proks.schoolpupilbook.shared.domain.Course;
import cz.proks.schoolpupilbook.shared.domain.User;
import cz.proks.schoolpupilbook.shared.domain.UserCourseRelation;
import cz.proks.schoolpupilbook.shared.util.Tester;

public class UserCourseRelationConverter implements Converter<UserCourseRelationDBO, UserCourseRelation>{
	@Override
	public UserCourseRelationDBO getDBO(UserCourseRelation domain) {
		if (domain == null)
			return null;
		
		UserCourseRelationDBO dbo = new UserCourseRelationDBO();
		
		if (!Tester.isEmpty(domain.getId()))
			dbo.setId(KeyFactory.stringToKey(domain.getId()));
		
		dbo.setUserKey(KeyFactory.stringToKey(domain.getUser().getId()));
		dbo.setCourseKey(KeyFactory.stringToKey(domain.getCourse().getId()));
		
		return dbo;
	}
	
	@Override
	public UserCourseRelation getDomain(UserCourseRelationDBO dbo) {
		if (dbo == null)
			return null;
		
		UserDAO userDao = new UserDAO();
		CourseDAO courseDao = new CourseDAO();
		
		User user = userDao.find(dbo.getUserKey());
		Course course = courseDao.find(dbo.getCourseKey());
		
		UserCourseRelation domain = new UserCourseRelation();
		domain.setId(KeyFactory.keyToString(dbo.getId()));
		domain.setUser(user);
		domain.setCourse(course);
		
		return domain;
	}
}
